import { ref } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'

export const useThemeMode = () => {
  const isLight = ref()

  // Initialize theme style following system
  const themeMode = localStorage.getItem('themeMode')
  if (themeMode) {
    document.documentElement.setAttribute('theme-mode', themeMode)
    isLight.value = themeMode !== 'light'
  } else {
    // Obtain system theme
    const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    const themeMode = darkModeMediaQuery.matches ? 'dark' : 'light'
    localStorage.setItem('themeMode', themeMode)
    document.documentElement.setAttribute('theme-mode', themeMode)
    isLight.value = themeMode === 'dark'
  }

  // Change theme mode
  const changeThemeMode = async () => {
    isLight.value = !isLight.value
    const themeMode = isLight.value ? 'dark' : 'light'
    document.documentElement.setAttribute('theme-mode', themeMode)
    localStorage.setItem('themeMode', themeMode)
    MessagePlugin.closeAll()
    await MessagePlugin.info(themeMode == 'light' ? '已经入浅色模式！' : '已进入深色模式！')
  }

  return {
    isLight,
    changeThemeMode
  }
}
